package piwan.gui;

import org.fenggui.Display;
import org.fenggui.FengGUI;
import org.fenggui.Label;
import org.fenggui.binding.render.text.ITextRenderer;
import org.fenggui.util.Alignment;
import org.fenggui.util.Point;

public class LabelTable {
	private Label[] names, values;
	private static final int yspacing = 5, xspacing = 10;
	private Display d;
	
	public LabelTable(Display d, int fieldCount, ITextRenderer trname, ITextRenderer trval) {
		this.d = d;
		names = new Label[fieldCount];
		values = new Label[fieldCount];
		for(int i=0; i<fieldCount; ++i) {
			names[i] = FengGUI.createWidget(Label.class);
			values[i] = FengGUI.createWidget(Label.class);
			
			names[i].getAppearance().addRenderer("default", trname);
			names[i].getAppearance().setAlignment(Alignment.LEFT);
			
			values[i].getAppearance().addRenderer("default", trval);
			values[i].getAppearance().setAlignment(Alignment.MIDDLE);
			d.addWidget(names[i],values[i]);
		}
	}
	
	public void removeWidgets() {
		for(int i=0; i<names.length; ++i)
			d.removeWidget(names[i],values[i]);
	}
	
	public void setName(int i, String str)	{ names[i].setText(str); }
	public void setValue(int i, String str)	{ values[i].setText(str); }
	public int getHeight() { return names[0].getHeight() * (names.length + yspacing); }
	public void position(int centerX, int bottomY) {
		int maxNameWidth = -1;
		int maxValWidth = -1;
		int heightUnit = names[0].getHeight();
		for(int i=0; i<names.length; ++i) {
			if(maxNameWidth < names[i].getWidth())
				maxNameWidth = names[i].getWidth();
			if(maxValWidth < values[i].getWidth())
				maxValWidth = values[i].getWidth();
		}
		
		int topY = bottomY + getHeight()-yspacing;
		int namex = centerX - (maxNameWidth+maxValWidth+xspacing)/2;
		int valuex = namex + maxNameWidth + xspacing;
		for(int i=0; i<names.length; ++i) {
			int y = topY - heightUnit*i;
			values[i].setSize(maxValWidth, heightUnit);
			names[i].setPosition(new Point(namex,y));
			values[i].setPosition(new Point(valuex,y));
		}
	}
}
